#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

struct Line {
    std::string content;
    bool isSection{};
    bool isKeyValue{};
    std::string section;
    std::string key;
    std::string value;
};

std::vector<Line> readIniFile(const std::string& filename) {
    std::ifstream file(filename);
    std::vector<Line> lines;
    std::string line;
    std::string currentSection;

    while (std::getline(file, line)) {
        Line l;
        l.content = line;
        l.isSection = false;
        l.isKeyValue = false;

        if (line.empty() || line[0] == ';' || line[0] == '#') {
            // 空行或注释行
        } else if (line[0] == '[' && line.back() == ']') {
            // 节
            l.isSection = true;
            currentSection = line.substr(1, line.size() - 2);
            l.section = currentSection;
        } else {
            // 键值对
            size_t pos = line.find('=');
            if (pos != std::string::npos) {
                l.isKeyValue = true;
                l.section = currentSection;
                l.key = line.substr(0, pos);
                l.value = line.substr(pos + 1);
            }
        }

        lines.push_back(l);
    }

    return lines;
}

void setKeyValue(std::vector<Line>& lines, const std::string& section, const std::string& key, const std::string& value) {
    bool sectionFound = false;
    for (auto& line : lines) {
        if (line.isSection && line.section == section) {
            sectionFound = true;
        } else if (sectionFound && line.isKeyValue && line.key == key) {
            line.value = value;
            line.content = key + "=" + value;
            return;
        }
    }

    // 如果节或键不存在，添加新的键值对
    if (sectionFound) {
        lines.push_back({key + "=" + value, false, true, section, key, value});
    } else {
        lines.push_back({"[" + section + "]", true, false, section, "", ""});
        lines.push_back({key + "=" + value, false, true, section, key, value});
    }
}

void writeIniFile(const std::string& filename, const std::vector<Line>& lines) {
    std::ofstream file(filename);
    for (const auto& line : lines) {
        file << line.content << std::endl;
    }
    file.close();
}

int main() {
    std::string filename = "../sysconfig.ini";
    auto lines = readIniFile(filename);

    setKeyValue(lines, "Settings", "Volume", "75");

    writeIniFile("../sysconfig2.ini", lines);

    return 0;
}


